/**
 * XMLMod
 * This utility is designed to allow modification of an xml file 
 * via an Ant call.  See the documentation for usage examples
 */
package com.xmlmod.util;

import java.lang.reflect.Field;

/**
 * @author W. Cowger
 *
 */
public class XMLModResource {
	Class resource;
	boolean verbose = false;
	
	// Disable the default contructor to force the static factory to be used
	private XMLModResource(){
		
	}
	
	private XMLModResource(String resourcePath){
		ClassLoader classLoader = XMLModResource.class.getClassLoader();
		try {
			Class resource = classLoader.loadClass(resourcePath);
			this.resource = resource;
		} catch (ClassNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
	public static XMLModResource getResource(String resourcePath){
		XMLModResource  resource = new XMLModResource(resourcePath);
		
		return resource;
	}
	
	public String getMessage(String message){
		String resourceMessage = "";
		
		try {
			Field field = resource.getField(message);
			if(field != null){
				resourceMessage = field.get(null).toString();
			}
		} catch (SecurityException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (NoSuchFieldException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IllegalArgumentException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IllegalAccessException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return resourceMessage;
	}
	
	public String getMessage(String message, String... params){
		String resourceMessage = getMessage(message);
		
		log("ResourceMessage: " + resourceMessage);
		
		for(int i=1; i<params.length + 1; i++){
			log("i: " + i);
			resourceMessage = resourceMessage.replaceAll("%" + (new Integer(i)).toString(), params[i - 1]);
		}
		
		return resourceMessage;
	}
	
	private void log(String message){
		if(verbose){
			System.out.println(message);
		}
	}
}
